package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"gogogo/gorm/model"
)
import 	_ "github.com/go-sql-driver/mysql"

/*
   Author: mahaiyuan
   Date: 2021/2/24 7:07 下午
   Description:
*/

func main() {
	db, err := gorm.Open("mysql", "root:12345678@tcp(localhost:3306)/gogogo?charset=utf8mb4&parseTime=True&loc=Local")
	db.LogMode(true)	//开启日志 打印执行的sql
	db.SingularTable(true)
	if err != nil {
		fmt.Println("error happen", err)
		panic("fail to connect db")
	}
	defer db.Close()
	//var teacher model.Teacher
	// 查询首条
	// SELECT * FROM `teacher`   ORDER BY `teacher`.`id` ASC LIMIT 1
	//db.First(&teacher)
	//fmt.Printf("teacher = %v \n", teacher)

	/*var teachers []model.Teacher
	// 按主键批量查询
	// SELECT * FROM `teacher`  WHERE (`teacher`.`id` IN (1,4))
	db.Find(&teachers, []int64{1, 4})
	fmt.Printf("teachers = %v \n", teachers)*/

	// 条件检索
	var teacher model.Teacher
	//SELECT * FROM `teacher`  WHERE (job_number = '20210010001') ORDER BY `teacher`.`id` ASC LIMIT 1
	//db.Where("job_number = ?", "20210010001").First(&teacher)
	//fmt.Printf("teacher = %v \n", teacher)

	//SELECT * FROM `teacher`  WHERE (job_number = '20210010001' AND work_age = 3) ORDER BY `teacher`.`id` ASC LIMIT 1
	//db.Where("job_number = ? AND work_age = ?", "20210010001", 3).First(&teacher)

	//SELECT * FROM `teacher`  WHERE (`teacher`.`job_number` = '001') ORDER BY `teacher`.`id` ASC LIMIT 1
	//db.Where(&model.Teacher{JobNumber: "001"}).First(&teacher)

	// 查询指定字段
	// SELECT job_number FROM `teacher`  WHERE (work_age < 20) ORDER BY `teacher`.`id` ASC LIMIT 1
	//db.Select("job_number").Where("work_age < ?", 20).First(&teacher)
	//SELECT id, job_number FROM `teacher`  WHERE (work_age < 20) ORDER BY `teacher`.`id` ASC LIMIT 1
	db.Select([]string{"id", "job_number"}).Where("work_age < ?", 20).First(&teacher)
	fmt.Printf("teacher = %v \n", teacher)

	var count int64
	// 查询数量
	// SELECT count(*) FROM `teacher`
	//db.Model(&model.Teacher{}).Count(&count)
	//SELECT count(1) FROM `teacher`
	db.Table("teacher").Select("count(1)").Count(&count)
	fmt.Println("count =", count)

	// 原生SQL
	//select * from teacher where id = 1
	//db.Raw("select * from teacher where id = ?", 1).Scan(&teacher)
	//select id,job_number from teacher where id = 1
	//db.Raw("select id,job_number from teacher where id = ?", 1).Scan(&teacher)
	fmt.Printf("teacher = %v \n", teacher)

}
